home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!news
- From: watzka@stat.uni-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: How to use assert( )
- Date: 11 Apr 1996 09:19:39 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4kiirb$hll@sparcserver.lrz-muenchen.de>
- References: <4kc3k7$dur@orion.cybercom.net> <316be48b.3354928@news.netvision.net.il>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- zivshosh@netvision.net.il ( Ziv) writes:
-
- >On Mon, 08 Apr 1996 21:22:15 GMT, nield@cybercom.net (John Nield)
- >wrote:
-
- >>I am interested in the use of the assert() library function (macro?).
- >>Neither the FAQ, nor K&R seems to have anything about it. Could
- >>someone help me with a breif explanation of its uses and mabye some
- >>example code?
- >>
- >>I'm just starting my first project big enough to split among many
- >>people, and from the vague explanations I've heard, assert is supposed
- >>to be a usefull way to cause errors when someone passes your code bad
- >>values. How do I do this?
- >>
- >>thanx,
- >>
- >>;john nield
- >>
- >Suppose you read a number x which should be between xmin and xmax
- >after the reading you could write (assuming <assert.h> is #included)
- >assert( x >= xmin && x <= xmax);
-
- This is how the macro assert() can be used in quick hacks. In real
- programs (i.e. programs that will be used more than once or twice),
- you usually check user input.
-
- OTOH, if you have an algorithm that computes, e.g., a probability,
- then you know that the computed result will _always_ fall between
- two limits (0 and 1). So, in a function that returns a probability
- in "res", the following statements might be useful to detect errors:
-
- assert(0.0 <= res && res <= 1.0);
- return res;
- }
-
- The end user should never see the output of an assertion in an ideal
- world. One reason for this is that a final build should be translated
- with NDEBUG defined. The other (more optimistic) reason is, that all
- possible problems that make an assertion fail should have been
- detected during testing.
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
-